﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;

namespace XDSoft.Web
{
    /// <summary>
    /// UploadIMG 的摘要说明
    /// </summary>
    public class UploadIMG
    {
        public UploadIMG()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        private string _MSG;
        private string _ofullname;
        private string _tfullname;
        private string _ofilename;
        private string _tfilename;
        private int _limitwidth = 2048;
        private int _limitheight = 1536;
        private int _twidth = 100;
        private int _theight = 100;
        private int _size = 1000000;
        private bool _israte = true;
        private string _path = "UploadFiles";
        /// <summary>
        /// 信息
        /// </summary>
        public string MSG
        {
            get { return _MSG; }
            set { _MSG = value; }
        }
        /// <summary>
        /// 保存时的完整路径.原图
        /// </summary>
        public string OFullName
        {
            get { return _ofullname; }
            set { _ofullname = value; }
        }
        /// <summary>
        /// 保存时的完整路径.缩略图
        /// </summary>
        public string TFullName
        {
            get { return _tfullname; }
            set { _tfullname = value; }
        }
        /// <summary>
        /// 保存时的图片名称.原图
        /// </summary>
        public string OFileName
        {
            get { return _ofilename; }
            set { _ofilename = value; }
        }
        /// <summary>
        /// 保存时的图片名称.缩略图
        /// </summary>
        public string TFileName
        {
            get { return _tfilename; }
            set { _tfilename = value; }
        }
        /// <summary>
        /// 限定宽度
        /// </summary>
        public int LimitWidth
        {
            get { return _limitwidth; }
            set { _limitwidth = value; }
        }
        /// <summary>
        /// 限定高度
        /// </summary>
        public int LimitHeight
        {
            get { return _limitheight; }
            set { _limitheight = value; }
        }
        /// <summary>
        /// 缩略图宽度
        /// </summary>
        public int TWidth
        {
            get { return _twidth; }
            set { _twidth = value; }
        }
        /// <summary>
        /// 缩略图高度
        /// </summary>
        public int THeight
        {
            get { return _theight; }
            set { _theight = value; }
        }
        /// <summary>
        /// 文件大小
        /// </summary>
        public int Size
        {
            get { return _size; }
            set { _size = value; }
        }
        /// <summary>
        /// 是否成比例
        /// </summary>
        public bool IsRate
        {
            get { return _israte; }
            set { _israte = value; }
        }
        /// <summary>
        /// 存放图片的文件夹名称
        /// </summary>
        public string Path
        {
            get { return _path; }
            set { _path = value; }
        }

        /// <summary>
        /// 图片上传(默认:"等比压缩,限定上传尺寸2048*1536,缩略图尺寸100*100,限定上传大小1MB,存放在根目录UpdateFile中")
        /// </summary>
        /// <param name="UploadFile">文件上传控件</param>
        /// <returns>返回是否成功保存图片</returns>
        public bool UpLoadIMG(FileUpload UploadFile)
        {
            if (UploadFile.HasFile)//检查是否已经选择文件
            {
                string filename = UploadFile.FileName.ToLower();
                int i = filename.LastIndexOf(".");
                filename = filename.Substring(i, filename.Length - i);
                if (!(filename == ".jpg" || filename == ".jpeg" || filename == ".gif" || filename == ".png" || filename == ".bmp"))
                {
                    MSG = "不受支持的类型,请重新选择!";
                    return false;
                }//检查上传文件的格式是否有效
                if (UploadFile.PostedFile.ContentLength == 0 || UploadFile.PostedFile.ContentLength >= Size)
                {
                    MSG = "指定的文件大小不符合要求!";
                    return false;
                }//检查图片文件的大小
                //生成原图 
                Stream oStream = UploadFile.PostedFile.InputStream;
                System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
                int owidth = oImage.Width; //原图宽度 
                int oheight = oImage.Height; //原图高度
                if (owidth > LimitWidth || oheight > LimitHeight)
                {
                    MSG = "超过允许的图片尺寸范围!";
                    return false;
                }//检查是否超出规定尺寸
                if (IsRate)
                {
                    //按比例计算出缩略图的宽度和高度 
                    if (owidth >= oheight)
                    {
                        THeight = (int)Math.Floor(Convert.ToDouble(oheight) * (Convert.ToDouble(TWidth) / Convert.ToDouble(owidth)));//等比设定高度
                    }
                    else
                    {
                        TWidth = (int)Math.Floor(Convert.ToDouble(owidth) * (Convert.ToDouble(THeight) / Convert.ToDouble(oheight)));//等比设定宽度
                    }
                }
                //生成缩略原图 
                Bitmap tImage = new Bitmap(TWidth, THeight);
                Graphics g = Graphics.FromImage(tImage);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法 
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度 
                g.Clear(Color.Transparent); //清空画布并以透明背景色填充 
                g.DrawImage(oImage, new Rectangle(0, 0, TWidth, THeight), new Rectangle(0, 0, owidth, oheight), GraphicsUnit.Pixel);
                Random oRandom = new Random();
                string oStringRandom = oRandom.Next(9999).ToString();//生成4位随机数字
                //格式化日期作为文件名
                DateTime oDateTime = new DateTime();
                oDateTime = DateTime.Now;
                string oStringTime = oDateTime.ToString();
                oStringTime = oStringTime.Replace("-", "");
                oStringTime = oStringTime.Replace(" ", "");
                oStringTime = oStringTime.Replace(":", "");
                OFileName = "o" + oStringTime + oStringRandom + filename;
                TFileName = "t" + oStringTime + oStringRandom + filename;
                string oSavePath = HttpContext.Current.Server.MapPath("~") + "\\" + Path + "\\";
                if (!Directory.Exists(oSavePath))
                {
                    Directory.CreateDirectory(oSavePath);//在根目录下建立文件夹
                }
                //保存路径+完整文件名
                OFullName = oSavePath + OFileName;
                TFullName = oSavePath + TFileName;
                //开始保存图片至服务器
                try
                {
                    switch (filename)
                    {
                        case ".jpeg":
                        case ".jpg":
                            {
                                oImage.Save(OFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
                                tImage.Save(TFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
                                break;
                            }
                        case ".gif":
                            {
                                oImage.Save(OFullName, System.Drawing.Imaging.ImageFormat.Gif);
                                tImage.Save(TFullName, System.Drawing.Imaging.ImageFormat.Gif);
                                break;
                            }
                        case ".png":
                            {
                                oImage.Save(OFullName, System.Drawing.Imaging.ImageFormat.Png);
                                tImage.Save(TFullName, System.Drawing.Imaging.ImageFormat.Png);
                                break;
                            }
                        case ".bmp":
                            {
                                oImage.Save(OFullName, System.Drawing.Imaging.ImageFormat.Bmp);
                                tImage.Save(TFullName, System.Drawing.Imaging.ImageFormat.Bmp);
                                break;
                            }
                    }
                    MSG = "图片上传成功!";
                    return true;
                }
                catch (Exception ex)
                {
                    MSG = ex.Message;
                    return false;
                }
                finally
                {
                    //释放资源 
                    oImage.Dispose();
                    g.Dispose();
                    tImage.Dispose();
                }
            }
            else
            {
                MSG = "请先选择需要上传的图片!";
                return false;
            }
        }
    }

    /// <summary> 
    /// 非寒上传类（图片）。 作者:非寒．功能：上传文件操作(主要用于图片上传);
    /// </summary> 
    public class Uploader
    {
        private int _Error = 0;//返回上传状态。 
        private int _MaxSize = 5120000;//最大单个上传文件 (默认)
        private string _FileType = "jpg/gif/bmp/png";//所支持的上传类型用"/"隔开 
        private string _SavePath = System.Web.HttpContext.Current.Server.MapPath(".") + "\\uploadFiles";//保存文件的实际路径 
        private int _SaveType = 0;//上传文件的类型，0代表自动生成文件名 
        private HtmlInputFile _FormFile;//上传控件。 
        private string _InFileName = "";//非自动生成文件名设置。 
        private string _OutFileName = "";//输出文件名。 
        private bool _IsCreateImg = true;//是否生成缩略图。 
        private bool _Iss = false;//是否有缩略图生成.
        private int _Height = 0;//获取上传图片的高度 
        private int _Width = 0;//获取上传图片的宽度 
        private int _sHeight = 120;//设置生成缩略图的高度 
        private int _sWidth = 120;//设置生成缩略图的宽度
        private bool _IsDraw = false;//设置是否加水印
        private int _DrawStyle = 0;//设置加水印的方式０：文字水印模式，１：图片水印模式,2:不加
        private int _DrawString_x = 10;//绘制文本的Ｘ坐标（左上角）
        private int _DrawString_y = 10;//绘制文本的Ｙ坐标（左上角）
        private string _AddText = "杭州五维多媒体\nHTTP://WWW.5D.CN";//设置水印内容
        private string _Font = "宋体";//设置水印字体
        private int _FontSize = 12;//设置水印字大小
        private int _FileSize = 0;//获取已经上传文件的大小
        private string _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(".") + "/images/5dm_new.jpg";//图片水印模式下的覆盖图片的实际地址

        /// <summary>
        /// Error返回值，1、没有上传的文件。2、类型不允许。3、大小超限。4、未知错误。0、上传成功。 
        /// </summary>
        public int Error
        {
            get { return _Error; }
        }
        /// <summary>
        /// 最大单个上传文件
        /// </summary>
        public int MaxSize
        {
            set { _MaxSize = value; }
        }
        /// <summary>
        /// 所支持的上传类型用"/"隔开 
        /// </summary>
        public string FileType
        {
            set { _FileType = value; }
        }
        /// <summary>
        /// //保存文件的实际路径 
        /// </summary>
        public string SavePath
        {
            set { _SavePath = System.Web.HttpContext.Current.Server.MapPath(value); }
            get { return _SavePath; }
        }
        /// <summary>
        /// 上传文件的类型，0代表自动生成文件名
        /// </summary>
        public int SaveType
        {
            set { _SaveType = value; }
        }
        /// <summary>
        /// 上传控件
        /// </summary>
        public HtmlInputFile FormFile
        {
            set { _FormFile = value; }
        }
        /// <summary>
        /// //非自动生成文件名设置。
        /// </summary>
        public string InFileName
        {
            set { _InFileName = value; }
        }
        /// <summary>
        /// 输出文件名
        /// </summary>
        public string OutFileName
        {
            get { return _OutFileName; }
            set { _OutFileName = value; }
        }
        /// <summary>
        /// 是否有缩略图生成.
        /// </summary>
        public bool Iss
        {
            get { return _Iss; }
        }
        /// <summary>
        /// //获取上传图片的宽度
        /// </summary>
        public int Width
        {
            get { return _Width; }
        }
        /// <summary>
        /// //获取上传图片的高度
        /// </summary>
        public int Height
        {
            get { return _Height; }
        }
        /// <summary>
        /// 设置缩略图的宽度
        /// </summary>
        public int sWidth
        {
            get { return _sWidth; }
            set { _sWidth = value; }
        }
        /// <summary>
        /// 设置缩略图的高度
        /// </summary>
        public int sHeight
        {
            get { return _sHeight; }
            set { _sHeight = value; }
        }
        /// <summary>
        /// 是否生成缩略图
        /// </summary>
        public bool IsCreateImg
        {
            get { return _IsCreateImg; }
            set { _IsCreateImg = value; }
        }
        /// <summary>
        /// 是否加水印
        /// </summary>
        public bool IsDraw
        {
            get { return _IsDraw; }
            set { _IsDraw = value; }
        }
        /// <summary>
        /// 设置加水印的方式０：文字水印模式，１：图片水印模式,2:不加
        /// </summary>
        public int DrawStyle
        {
            get { return _DrawStyle; }
            set { _DrawStyle = value; }
        }
        /// <summary>
        /// 绘制文本的Ｘ坐标（左上角）
        /// </summary>
        public int DrawString_x
        {
            get { return _DrawString_x; }
            set { _DrawString_x = value; }
        }
        /// <summary>
        /// 绘制文本的Ｙ坐标（左上角）
        /// </summary>
        public int DrawString_y
        {
            get { return _DrawString_y; }
            set { _DrawString_y = value; }
        }
        /// <summary>
        /// 设置文字水印内容
        /// </summary>
        public string AddText
        {
            get { return _AddText; }
            set { _AddText = value; }
        }
        /// <summary>
        /// 设置文字水印字体
        /// </summary>
        public string Font
        {
            get { return _Font; }
            set { _Font = value; }
        }
        /// <summary>
        /// 设置文字水印字的大小
        /// </summary>
        public int FontSize
        {
            get { return _FontSize; }
            set { _FontSize = value; }
        }
        public int FileSize
        {
            get { return _FileSize; }
            set { _FileSize = value; }
        }
        /// <summary>
        /// 图片水印模式下的覆盖图片的实际地址
        /// </summary>
        public string CopyIamgePath
        {
            set { _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(value); }
        }

        //获取文件的后缀名 
        private string GetExt(string path)
        {
            return Path.GetExtension(path);
        }
        //获取输出文件的文件名。 
        private string FileName(string Ext)
        {
            if (_SaveType == 0 || _InFileName.Trim() == "")
                return DateTime.Now.ToString("yyyyMMddHHmmssfff") + Ext;
            else
                return _InFileName;
        }
        //检查上传的文件的类型，是否允许上传。 
        private bool IsUpload(string Ext)
        {
            Ext = Ext.Replace(".", "");
            bool b = false;
            string[] arrFileType = _FileType.Split(';');
            foreach (string str in arrFileType)
            {
                if (str.ToLower() == Ext.ToLower())
                {
                    b = true;
                    break;
                }
            }
            return b;
        }
        //上传主要部分。 
        public void Open()
        {
            HttpPostedFile hpFile = _FormFile.PostedFile;
            if (hpFile == null || hpFile.FileName.Trim() == "")
            {
                _Error = 1;
                return;
            }

            string Ext = GetExt(hpFile.FileName);
            if (!IsUpload(Ext))
            {
                _Error = 2;
                return;
            }

            int iLen = hpFile.ContentLength;
            if (iLen > _MaxSize)
            {
                _Error = 3;
                return;
            }

            try
            {

                if (!Directory.Exists(_SavePath))
                    Directory.CreateDirectory(_SavePath);
                byte[] bData = new byte[iLen];
                hpFile.InputStream.Read(bData, 0, iLen);
                string FName;
                FName = FileName(Ext);
                string TempFile = "";
                if (_IsDraw)
                {
                    TempFile = FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString();
                }
                else
                {
                    TempFile = FName;
                }
                FileStream newFile = new FileStream(_SavePath + TempFile, FileMode.Create);
                newFile.Write(bData, 0, bData.Length);
                newFile.Flush();
                int _FileSizeTemp = hpFile.ContentLength;

                if (_IsDraw)
                {
                    if (_DrawStyle == 0)
                    {
                        System.Drawing.Image Img1 = System.Drawing.Image.FromStream(newFile);
                        Graphics g = Graphics.FromImage(Img1);
                        g.DrawImage(Img1, 100, 100, Img1.Width, Img1.Height);
                        Font f = new Font(_Font, _FontSize);
                        Brush b = new SolidBrush(Color.Red);
                        string addtext = _AddText;
                        g.DrawString(addtext, f, b, _DrawString_x, _DrawString_y);
                        g.Dispose();
                        Img1.Save(_SavePath + FName);
                        Img1.Dispose();


                    }
                    else
                    {
                        System.Drawing.Image image = System.Drawing.Image.FromStream(newFile);
                        System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_CopyIamgePath);
                        Graphics g = Graphics.FromImage(image);
                        g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - 5, image.Height - copyImage.Height - 5, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                        g.Dispose();
                        image.Save(_SavePath + FName);
                        image.Dispose();
                    }
                }

                try
                {
                    //获取图片的高度和宽度
                    System.Drawing.Image Img = System.Drawing.Image.FromStream(newFile);
                    _Width = Img.Width;
                    _Height = Img.Height;
                    //生成缩略图部分 
                    if (_IsCreateImg)
                    {
                        //如果上传文件小于15k，则不生成缩略图。 
                        if (iLen > 15360)
                        {

                            System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero);
                            newImg.Save(_SavePath + FName.Split('.').GetValue(0).ToString() + "_s." + FName.Split('.').GetValue(1).ToString());
                            newImg.Dispose();
                            _Iss = true;
                        }
                    }
                    if (_IsDraw)
                    {
                        if (File.Exists(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString()))
                        {
                            newFile.Dispose();
                            File.Delete(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString());
                        }
                    }
                }
                catch { }
                newFile.Close();
                newFile.Dispose();
                _OutFileName = FName;
                _FileSize = _FileSizeTemp;
                _Error = 0;
                return;
            }
            catch
            {
                _Error = 4;
                return;
            }
        }
    }


    /// <summary>
    /// UImage 的摘要说明。
    /// </summary>
    public class UploadImage : System.Web.UI.Page
    {
        bool _imgThumbnail = false;
        bool _imgLogo = false;

        /// <summary>
        /// 是否生成缩略图默认false
        /// </summary>
        public bool ImgThumbnail { get; set; }
        /// <summary>
        /// 是否生成水印(要生成水印必须在网站目录UploadFiles里设置对应的slogo.gif)
        /// </summary>
        public bool ImgLogo { get; set; }

        public UploadImage()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        public string UpLoadFiles(FileUpload uploadFile, out string strErrorMessage)
        {
            strErrorMessage = string.Empty;
            string strAllowExt = "gif,jpg,jpeg,bmp,png";
            string strServerPath = string.Empty;
            string strSavePath = string.Empty;
            string strLogoImagePath = string.Empty;
            int iSize = 1024 * 1024 * 3;

            strServerPath = HttpContext.Current.Request.PhysicalApplicationPath;
            strSavePath = strServerPath + "UploadFiles";
            strLogoImagePath = strServerPath + "UploadFiles" + "\\slogo.gif";

            if (uploadFile.PostedFile == null)
            {
                strErrorMessage = "检查上传的图片";
                return null;
            }

            int iContentLength = uploadFile.PostedFile.ContentLength;
            if (iContentLength > iSize)
            {
                strErrorMessage = "检查上传的图片大小不能超过:" + iSize.ToString();
                return null;
            }

            string strExtName = string.Empty;
            int iPos = uploadFile.PostedFile.FileName.LastIndexOf(".");
            if (iPos != -1)
            {
                strExtName = uploadFile.PostedFile.FileName.Substring(iPos + 1).ToLower();
            }

            if (string.IsNullOrEmpty(strExtName))
            {
                strErrorMessage = "上传图片格式错误";
                return null;
            }

            if (strAllowExt.ToLower().IndexOf(strExtName) < 0)
            {
                strErrorMessage = "上传图片格式错误";
                return null;
            }

            DateTime dateTime = DateTime.Now;

            string strBasePath = dateTime.Year + "\\" + dateTime.Month + "\\" + dateTime.Day; // 按日期生成的文件名 可包括类型
            string strFileName = dateTime.ToString("yyyyMMddHHmmssffff");
            string strSmallImagePath = strSavePath + "\\" + strBasePath + "\\" + "Small";    //缩略图路径 
            string strBigImagePath = strSavePath + "\\" + strBasePath + "\\" + "Big";        //原始图路径 //水印图路径 

            string strOldName = strBigImagePath + "\\" + strFileName + "." + strExtName;       //原始图路径和名称
            string strSmallName = strSmallImagePath + "\\" + strFileName + "." + strExtName;   //缩略图路径和名称  
            string strWaterName = strBigImagePath + "\\T_" + strFileName + "." + strExtName;   //水印图路径和名称

            try
            {
                if (!Directory.Exists(strSmallImagePath))
                    Directory.CreateDirectory(strSmallImagePath);
                if (!Directory.Exists(strBigImagePath))
                    Directory.CreateDirectory(strBigImagePath);
            }
            catch(Exception ex)
            {
                strErrorMessage = "上传图片失败，" + ex.Message;
                return null;
            }

            Graphics g = null;
            //上传的图片流
            System.Drawing.Image imgUpload = null;
            //生成的缩略图
            System.Drawing.Image imgThumbnail = null;
            //水印图片
            System.Drawing.Image imgLogo = null;

            try
            {

                Stream streamUpLoadFile = uploadFile.PostedFile.InputStream;
                imgUpload = System.Drawing.Image.FromStream(streamUpLoadFile);   //上传的图片 
                imgUpload.Save(strOldName);


                int width, height, newwidth, newheight;
                width = imgUpload.Width;
                height = imgUpload.Height;

                if (this.ImgThumbnail)
                {
                    if (width > height)
                    {
                        newwidth = 60;
                        newheight = (int)((double)height / (double)width * (double)newwidth);
                    }
                    else
                    {
                        newheight = 60;
                        newwidth = (int)((double)width / (double)height * (double)newheight);
                    }

                    System.Drawing.Image.GetThumbnailImageAbort callb = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                    imgThumbnail = imgUpload.GetThumbnailImage(newwidth, newheight, callb, IntPtr.Zero);

                    imgThumbnail.Save(strSmallName);
                }

                if (this.ImgLogo)
                {
                    imgLogo = System.Drawing.Image.FromFile(strLogoImagePath);
                    Bitmap bitmapSave = null;
                    bitmapSave = new Bitmap(imgUpload);
                    g = Graphics.FromImage(bitmapSave);
                    g.DrawImage(imgLogo, new Rectangle(width - imgLogo.Width, height - imgLogo.Height, width, height), 0, 0, width, height, GraphicsUnit.Pixel);
                    bitmapSave.Save(strWaterName);
                    bitmapSave.Dispose();
                }
                return strOldName.Replace(strServerPath, "");
            }
            catch (Exception ex)
            {
                strErrorMessage = "上传图片失败，" + ex.Message;
                return null;
            }
            finally
            {
                if (g != null)
                    g.Dispose();
                if (imgUpload != null)
                    imgUpload.Dispose();
                if (imgThumbnail != null)
                    imgThumbnail.Dispose();
                if (imgLogo != null)
                    imgLogo.Dispose();
            }
        }
        public bool ThumbnailCallback()
        {
            return false;
        }
    }


}
